package com.tsunami.authority.controller;

import com.tsunami.authority.model.Oauth2TokenDto;
import com.tsunami.base.R;
import com.tsunami.common.AuthConstant;
import com.tsunami.exception.code.ExceptionCode;
import com.tsunami.utils.DesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

/**
 * @author lx
 * @since 2021-11-10 10:04
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "AuthController", value = "认证中心登录认证")
@RequestMapping("/oauth")
public class AuthController {

    private final TokenEndpoint tokenEndpoint;

    @ApiOperation("Oauth2获取token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", value = "Oauth2客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", value = "Oauth2客户端秘钥", required = true),
            @ApiImplicitParam(name = "code", value = "授权码"),
            @ApiImplicitParam(name = "redirect_uri", value = "重定向地址"),
            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
            @ApiImplicitParam(name = "username", value = "登录用户名"),
            @ApiImplicitParam(name = "password", value = "登录密码"),
            @ApiImplicitParam(name = "timestamp", value = "加密戳")
    })
    @PostMapping(value = "/token")
    public R postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {

        String timestamp = parameters.get("timestamp");
        String username = DesUtil.decrypt(parameters.get("username").replace("%2B", "+"), timestamp);
        String password = DesUtil.decrypt(parameters.get("password").replace("%2B", "+"), timestamp);
        parameters.put("username", username);
        parameters.put("password", password);
        try {
            OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
            Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                    .token(oAuth2AccessToken.getValue())
                    .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                    .expiresIn(oAuth2AccessToken.getExpiresIn())
                    .tokenHead(AuthConstant.JWT_TOKEN_PREFIX).build();
            return R.ok().data("data", oauth2TokenDto);
        } catch (InvalidGrantException e) {
            return R.error().exCode(ExceptionCode.EX_USER_OR_PASSWORD);
        } catch (UsernameNotFoundException e){
            return R.error().exCode(ExceptionCode.NO_USER);
        }
    }

    @ApiOperation("Oauth2获取token")
    @PostMapping(value = "/WXOpenIdLogin")
    public R WXOpenIdLogin(){

        return R.ok();
    }
}